package com.lagou.dw.flume.interceptors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.event.SimpleEvent;
import org.apache.flume.interceptor.Interceptor;
import org.junit.Test;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LogTypeInterceptor implements Interceptor {
    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
        String eventBody = new String(event.getBody());
        Map<String, String> headers = event.getHeaders();
        String[] bodyArr = eventBody.split("\\s+");
        String timeStampString = "";
        try{
            String jsonStr = bodyArr[6];
            if (null == jsonStr) {
                return null;
            }
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            if ("start".equals(headers.getOrDefault("logtype", ""))) {
                timeStampString = jsonObject.getJSONObject("app_active").getString("time");
            } else if ("event".equals(headers.getOrDefault("logtype", ""))) {
                JSONObject jsonObject1 = (JSONObject) jsonObject.getJSONArray("lagou_event").get(0);
                timeStampString = jsonObject1.getString("time");
            }
            // 处理时间格式
            long timeStamp = Long.parseLong(timeStampString);
//            String date = formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeStamp), ZoneId.systemDefault()));
            String date = formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeStamp), ZoneId.of("GMT+8")));
            headers.put("logtime", date);
            event.setHeaders(headers);
        } catch (Exception e) {
            headers.put("logtime", "unknown");
            event.setHeaders(headers);
//            e.printStackTrace();
        }
        return event;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        ArrayList<Event> results = new ArrayList<>();
        for (Event e : list) {
            Event out = intercept(e);
            if (null != out) {
                results.add(out);
            }
        }
        return results;
    }

    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder {
        @Override
        public Interceptor build() {
            return new LogTypeInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }

    @Test
    public void testEvent() {
        String s = "2020-08-20 12:00:58.395 [main] INFO  com.lagou.ecommerce.AppEvent - {\"lagou_event\":[{\"name\":\"goods_detail_loading\",\"json\":{\"entry\":\"2\",\"goodsid\":\"0\",\"loading_time\":\"92\",\"action\":\"3\",\"staytime\":\"10\",\"showtype\":\"0\"},\"time\":1595265099584},{\"name\":\"notification\",\"json\":{\"action\":\"1\",\"type\":\"3\"},\"time\":1595300120620},{\"name\":\"ad\",\"json\":{\"duration\":\"10\",\"ad_action\":\"0\",\"shop_id\":\"23\",\"event_type\":\"ad\",\"ad_type\":\"1\",\"show_style\":\"0\",\"product_id\":\"36\",\"place\":\"placecampaign2_left\",\"sort\":\"1\"},\"time\":1595276738208}],\"attr\":{\"area\":\"东莞\",\"uid\":\"2F10092A0\",\"app_v\":\"1.1.0\",\"event_type\":\"common\",\"device_id\":\"1FB872-9A1000\",\"os_type\":\"1.1\",\"channel\":\"AD\",\"language\":\"chinese\",\"brand\":\"iphone-0\"}}";
        SimpleEvent simpleEvent = new SimpleEvent();
        simpleEvent.setBody(s.getBytes());
        HashMap<String, String> map = new HashMap<>();
        map.put("logtype", "event");
        simpleEvent.setHeaders(map);
        intercept(simpleEvent);
        System.out.println(simpleEvent.getHeaders().get("logtype"));
        System.out.println(simpleEvent.getHeaders().get("logtime"));
    }

    @Test
    public void testStart(){
        String s = "2020-08-20 11:56:08.211 [main] INFO  com.lagou.ecommerce.AppStart - {\"app_active\":{\"name\":\"app_active\",\"json\":{\"entry\":\"2\",\"action\":\"0\",\"error_code\":\"0\"},\"time\":1595288248066},\"attr\":{\"area\":\"三门峡\",\"uid\":\"2F10092A1\",\"app_v\":\"1.1.0\",\"event_type\":\"common\",\"device_id\":\"1FB872-9A1001\",\"os_type\":\"0.97\",\"channel\":\"WM\",\"language\":\"chinese\",\"brand\":\"xiaomi-3\"}}";
        SimpleEvent simpleEvent = new SimpleEvent();
        simpleEvent.setBody(s.getBytes());
        HashMap<String, String> map = new HashMap<>();
        map.put("logtype", "start");
        simpleEvent.setHeaders(map);
        intercept(simpleEvent);
        System.out.println(simpleEvent.getHeaders().get("logtype"));
        System.out.println(simpleEvent.getHeaders().get("logtime"));
    }

    @Test
    public void testTimeParse(){
//        System.out.println(formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(1595275979596L), ZoneId.systemDefault())));
        System.out.println(ZoneId.of("GMT+8"));
    }

}
